<template>
  <!-- 订单支付组件 -->
  <div v-loading="loading" element-loading-text="加载中">
    <div v-if="!errorMsg">
      <!-- 订单支付信息 -->
      <div class="order-info" v-if="!batPayId">
        <span>支付订单笔数：</span>
        <span class="font-red">{{ payForm.payOrderNum }}笔</span>
        <span>，支付总金额：</span>
        <span class="font-red">{{ payForm.payOrderAmount }}元</span>
      </div>
      <!-- 支付方式 -->
      <div v-if="payForm.result != 0 && payForm.result != 1" class="pay-type">
        <ul>
          <template v-for="(item, index) in payTypeList">
            <li v-if="item.showFlag" :class="item.selected ? 'li-border' : ''" :key="index" @click="doChangePayType(item)">
              <img v-if="item.selected" :src="item.borderImg" class="img-border">
              <img :src="item.logo">
              <span :class="item.fontColor" class="mar-l-10 font-16">{{ item.value }}</span>
            </li>
          </template>
        </ul>
      </div>
      <!-- 支付二维码 -->
      <div class="flex-center">
        <div v-if="payForm.result != 0 && payForm.result != 1" class="pay-code">
          <img :src="payForm.payCode" v-if="payForm.payCode">
          <p class="font-12">打开手机{{ payForm.payType == '36' ? '微信' : '支付宝' }}扫一扫继续付款</p>
        </div>
      </div>
      <!-- 支付结果 -->
      <div v-if="payForm.result == 0 || payForm.result == 1" class="pay-result">
        <img v-if="payForm.result == 0" :src="payFailImg">
        <img v-if="payForm.result == 1" :src="paySuccessImg">
        <p>{{ payForm.result === 1 ? '恭喜，你已支付成功！' : '抱歉，支付失败了！' }}</p>
      </div>
    </div>
    <div v-else style="text-align: center;">
      <img :src="payFailImg">
      <div class="mar-t-20 mar-b-10 font-20">
        <b>获取二维码异常：<span class="font-red">{{ errorMsg }}</span></b>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer mar-t-20">
      <el-button @click="doClose">关闭</el-button>
    </div>
  </div>
</template>

<script>
  import { getBatPayCode, checkBatPayStatus } from '@/api/goods/order'
  import { getBatPayCodeById } from '@/api/goods/bat-pay'
  import QRCode from 'qrcode'
  // 支付宝logo
  import alipayLogo from '@/assets/images/alipay-logo.png'
  // 微信logo
  import wepayLogo from '@/assets/images/wepay-logo.png'
  // 支付宝选中图片
  import alipaySel from '@/assets/images/alipay-sel.png'
  // 微信选中图片
  import wepaySel from '@/assets/images/wepay-sel.png'
  import payFail from '@/assets/images/pay-fail.png'
  import paySuccess from '@/assets/images/pay-success.png'

  export default {
    props: {
      showFlag: {
        type: Boolean,
        default() {
          return false
        }
      },
      // 支付订单id集合
      payOrderIds: {
        type: Array,
        default() {
          return []
        }
      },
      // 支付订单id
      batPayId: {
        type: String,
        default() {
          return ''
        }
      }
    },
    watch: {
      showFlag(val) {
        if (val) {
          this.init()
        }
      }
    },
    data() {
      return {
        // 支付表单
        payForm: {
          orderIds: [],
          batPayId: '',
          payType: '46',
          payOrderNum: '',
          payOrderAmount: '',
          payCode: '',
          enterprisePayFlag: 0
        },
        // 错误消息
        errorMsg: '',
        loading: false,
        // 支付成功图片
        paySuccessImg: paySuccess,
        // 支付失败图片
        payFailImg: payFail,
        // 定时轮询
        timeoutHandle: '',
        // 父页面刷新flag
        refreshFlag: false,
        // 支付类型数组
        payTypeList: [
          { key: '36', value: '微信支付', fontColor: 'font-green', logo: wepayLogo, borderImg: wepaySel, selected: false, showFlag: true },
          { key: '46', value: '支付宝', fontColor: 'font-blue', logo: alipayLogo, borderImg: alipaySel, selected: false, showFlag: true }
        ]
      }
    },
    // 初始化页面
    created() {
      this.init()
    },
    methods: {
      // 初始化
      init() {
        const originData = this.$options.data()
        this.payForm = originData.payForm
        this.refreshFlag = false
        this.errorMsg = ''
        this.payForm.orderIds = this.payOrderIds
        this.payForm.batPayId = this.batPayId
        this.payTypeList.forEach(item => {
          if (item.key === this.payForm.payType) {
            item.selected = true
          } else {
            item.selected = false
          }
        })
        this.getPayCode()
      },
      // 支付类型切换事件
      doChangePayType(item) {
        this.payTypeList.forEach(element => {
          element.selected = false
        })
        item.selected = true
        this.payForm.payType = item.key
        this.getPayCode()
      },
      // 获取二维码
      getPayCode() {
        this.loading = true
        this.errorMsg = ''
        if (this.payForm.batPayId) {
          getBatPayCodeById(this.payForm.batPayId, this.payForm.payType).then(response => {
            this.loading = false
            const data = response.data
            if (response.isError) {
              this.errorMsg = response.msg
              return
            }
            if (!data.resultData) {
              this.errorMsg = data.message
              return
            }
            const that = this
            QRCode.toDataURL(data.resultData).then(url => {
              that.$set(that.payForm, 'wechatPayCode', url)
              that.$set(that.payForm, 'payCode', url)
              that.handleBatPayByQRCode(data.batPayId)
            })
          })
        } else {
          getBatPayCode(this.payForm.orderIds.join(','), this.payForm.payType).then(response => {
            this.loading = false
            const data = response.data
            if (response.isError) {
              this.errorMsg = response.msg
              return
            }
            if (data.batPayList && data.batPayList.length > 0) {
              this.$router.push({ path: '/finace/bat-pay/index', query: { memberId: this.getMemberId() }})
              return
            }
            this.$set(this.payForm, 'payOrderNum', data.payOrderNum)
            this.$set(this.payForm, 'payOrderAmount', data.payOrderAmount)
            this.$set(this.payForm, 'enterprisePayFlag', data.enterprisePayFlag)
            const that = this
            if (!data.resultData) {
              that.errorMsg = data.message
              return
            }
            QRCode.toDataURL(data.resultData).then(url => {
              that.$set(that.payForm, 'wechatPayCode', url)
              that.$set(that.payForm, 'payCode', url)
              that.handleBatPayByQRCode(data.batPayId)
            })
          })
        }
      },
      // 轮询事件 验证扫码支付后状态
      handleBatPayByQRCode(batPayId) {
        if (this.timeoutHandle) {
          clearTimeout(this.timeoutHandle)
        }
        const that = this
        this.timeoutHandle = setTimeout(() => {
          checkBatPayStatus(batPayId).then(response => {
            if (response.isError) return
            if (response.data > 100) {
              // 已支付
              that.$set(that.payForm, 'result', 1)
              that.refreshFlag = true
            } else {
              that.handleBatPayByQRCode(batPayId)
            }
          })
        }, 3000)
      },
      // 关闭事件
      doClose() {
        if (this.timeoutHandle) {
          clearTimeout(this.timeoutHandle)
        }
        this.$emit('doClose', this.refreshFlag)
      }
    }
}
</script>

<style lang="less" scoped>
  .order-info {
    text-align: center;
    font-size: 18px;
  }
  .img-border {
    position: absolute;
    bottom: -1px;
    right: -1px;
    width: 30px;
    height: 24px;
  }
  .li-border {
    border: #00a1ef 1px solid;
    border-radius: 4px;
  }
  .pay-type {
    margin-top: 30px;
    margin-bottom: 10px;
    ul {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0;
      margin: 0;
      li {
        width: 150px;
        height: 50px;
        position: relative;
        background: #f8f8f8;
        border-radius: 4px;
        cursor: pointer;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 40px;
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
  .pay-code{
    img {
      padding: 10px;
      display: block;
      width: 168px;
      height: 168px;
      margin: 0 auto;
    }
    p {
      margin: 0;
    }
  }
  .pay-result {
    text-align: center;
    padding-top: 68px;
    img {
      width: 128px;
      height: 128px;
      display: block;
      margin: 0 auto;
    }
    p {
      font-size: 18px;
      color: #333;
      padding-top: 25px;
      margin: 0;
    }
  }
</style>